package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ServiceReservation;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.order.domain.Orders;
import com.ruoyi.order.service.IOrdersService;
import com.ruoyi.system.mapper.ServiceProviderMapper;
import com.ruoyi.system.mapper.ServiceTypeMapper;
import com.ruoyi.system.service.IServiceReservationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * APP端预约接口
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(AppointmentController.class);
    
    @Autowired
    private IServiceReservationService reservationService;
    
    @Autowired
    private ServiceProviderMapper providerMapper;
    
    @Autowired
    private ServiceTypeMapper serviceTypeMapper;
    
    @Autowired
    private IOrdersService ordersService;
    
    /**
     * APP端创建预约
     */
    @PostMapping("/create")
    public AjaxResult createReservationDirectly(@RequestBody Map<String, Object> appointmentData) {
        log.info("接收到预约请求: {}", appointmentData);
        
        try {
            // 解析前端传来的数据
            String staffIdStr = String.valueOf(appointmentData.get("staffId"));
            String staffName = String.valueOf(appointmentData.get("staffName"));
            String serviceType = String.valueOf(appointmentData.get("serviceType"));
            String appointmentDate = String.valueOf(appointmentData.get("appointmentDate"));
            String appointmentTime = String.valueOf(appointmentData.get("appointmentTime"));
            String contactName = String.valueOf(appointmentData.get("contactName"));
            String contactPhone = String.valueOf(appointmentData.get("contactPhone"));
            String remarks = appointmentData.get("remarks") != null ? String.valueOf(appointmentData.get("remarks")) : "";
            
            log.info("解析后的数据: staffId={}, staffName={}, serviceType={}, date={}, time={}, contactName={}, contactPhone={}", 
                    staffIdStr, staffName, serviceType, appointmentDate, appointmentTime, contactName, contactPhone);
            
            // 创建预约对象
            ServiceReservation reservation = new ServiceReservation();
            
            // 处理staffId，确保是数字
            Long staffId;
            try {
                staffId = Long.parseLong(staffIdStr);
                log.info("成功将staffId转换为Long类型: {}", staffId);
            } catch (NumberFormatException e) {
                log.error("服务人员ID格式错误: {}, 使用默认值", staffIdStr, e);
                staffId = 1L; // 默认值，避免出错
            }
            
            reservation.setProviderId(staffId);
            
            // 处理日期和时间
            try {
                LocalDate reservationDate = LocalDate.parse(appointmentDate);
                LocalTime reservationTime = LocalTime.parse(appointmentTime);
                reservation.setReservationDate(reservationDate);
                reservation.setReservationTime(reservationTime);
                log.info("成功解析日期和时间: {} {}", reservationDate, reservationTime);
            } catch (Exception e) {
                log.error("日期或时间格式错误: {} {}", appointmentDate, appointmentTime, e);
                return AjaxResult.error("日期或时间格式错误");
            }
            
            // 设置联系信息
            reservation.setContactName(contactName);
            reservation.setContactPhone(contactPhone);
            reservation.setRemark(remarks);
            
            // 设置状态为待确认
            reservation.setStatus("0");
            
            // 设置创建者和创建时间
            String username = SecurityUtils.getUsername();
            username = username != null && !username.isEmpty() ? username : "app_user";
            reservation.setCreateBy(username);
            reservation.setCreateTime(new Date());
            
            // 根据服务类型名称查询服务类型ID
            try {
                Long serviceTypeId = serviceTypeMapper.selectServiceTypeIdByName(serviceType);
                log.info("查询服务类型ID结果: serviceType={}, serviceTypeId={}", serviceType, serviceTypeId);
                
                if (serviceTypeId != null) {
                    reservation.setServiceTypeId(serviceTypeId);
                } else {
                    // 如果找不到对应的服务类型，使用默认值
                    log.warn("未找到服务类型: {}, 使用默认值", serviceType);
                    reservation.setServiceTypeId(1L);
                }
            } catch (Exception e) {
                log.error("查询服务类型ID出错", e);
                // 使用默认值
                reservation.setServiceTypeId(1L);
            }
            
            // 插入预约记录
            log.info("开始插入预约记录: {}", reservation);
            AjaxResult result = reservationService.insertServiceReservation(reservation);
            log.info("预约插入结果: {}", result);
            
            // 如果预约成功，创建订单
            if (result.isSuccess()) {
                // 创建订单
                Orders order = new Orders();
                order.setOrderNumber(generateOrderNumber());
                order.setCustomerName(contactName);
                order.setServiceContent(serviceType + " - " + staffName);
                order.setServicePrice(new BigDecimal("100.00")); // 默认价格
                order.setStatus("待确定");
                
                // 设置预约ID关联
                if (result.get("data") instanceof Long) {
                    Long reservationId = (Long) result.get("data");
                    order.setReservationId(reservationId);
                    log.info("关联预约ID: {}", reservationId);
                } else {
                    log.warn("未能获取预约ID，无法关联订单");
                }
                
                // 插入订单
                log.info("开始创建订单: {}", order);
                int orderResult = ordersService.insertOrders(order);
                if (orderResult > 0) {
                    log.info("订单创建成功: {}", order.getOrderNumber());
                } else {
                    log.error("订单创建失败");
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("创建预约失败", e);
            return AjaxResult.error("创建预约失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNumber() {
        // 生成订单号：当前时间戳 + 4位随机数
        String timestamp = String.valueOf(System.currentTimeMillis()).substring(5);
        String random = String.valueOf((int) (Math.random() * 9000) + 1000);
        return "BS" + timestamp + random;
    }
} 